import { GetServerSideProps, NextPage } from 'next'
import React, { useEffect } from 'react'
import dynamic from 'next/dynamic'
import cookie from 'cookie'

import { getProductById } from '~/services/product'
import { getIdFromSlug } from '~/libs/slug'
import { IProductDetail } from '~/types/product'

import { Seo } from '~/components/seo'
import { useRouter } from 'next/router'
import { useProductContext } from '@/contexts/ProductContext'

const BasicLayout = dynamic(() => import('@/core/components/layouts/BasicLayout'), { ssr: false })
const ProductDetail = dynamic(() => import('~/modules/product-detail'), { ssr: false })

type PageProps = {
  product: IProductDetail
}

export const getServerSideProps: GetServerSideProps<PageProps & { canonicalPath: string }> = async (context) => {
  const { slug } = context.query;
  const cookieString = context.req.headers.cookie;
  const cookies = cookieString ? cookie.parse(cookieString) : {};
  const auth = cookies?.auth ? JSON.parse(cookies.auth) : {};
  const tier = auth?.pricelist || '';

  const productId = getIdFromSlug(slug as string);
  const product = await getProductById(productId, tier);

  // ❌ produk tidak ada → 404
  if (!product) return { notFound: true };

  // ❌ tidak ada variants atau tidak ada yang harga > 0 → 404
  const hasValidVariant = Array.isArray(product.variants)
    && product.variants.some(v => (v?.price?.price ?? 0) > 0);
  if (!hasValidVariant) return { notFound: true };

  // Canonical path aman untuk SSR (hindari router.asPath di server)
  const canonicalPath = context.resolvedUrl || `/product/${slug}`;

  return { props: { product, canonicalPath } };
};


const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST

const ProductDetailPage: NextPage<PageProps & { canonicalPath: string }> = ({ product, canonicalPath }) => {
  const router = useRouter();
  const { setProduct } = useProductContext();

  useEffect(() => { if (product) setProduct(product); }, [product, setProduct]);

  const origin = process.env.NEXT_PUBLIC_SELF_HOST || '';
  const url = origin + (canonicalPath?.startsWith('/') ? canonicalPath : `/${canonicalPath}`);

  return (
    <BasicLayout>
      <Seo
        title={`${product.name} - Indoteknik.com`}
        description='Temukan pilihan produk B2B Industri &amp; Alat Teknik untuk Perusahaan, UMKM &amp; Pemerintah dengan lengkap, mudah dan transparan.'
        openGraph={{
          url,
          images: [{ url: product?.image, width: 800, height: 800, alt: product?.name }],
          type: 'product',
        }}
        additionalMetaTags={[{ name: 'keywords', content: `${product?.name}, Harga ${product?.name}, Beli ${product?.name}, Spesifikasi ${product?.name}` }]}
        canonical={url}
      />

      <div className='md:container pt-4 md:pt-6'>
        <ProductDetail product={product} />
      </div>
    </BasicLayout>
  );
};


export default ProductDetailPage